#pragma once

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "app.hpp"

const int defaultfd = -1;
const std::string defaultip = "0.0.0.0";//云服务器默认通信ip
const int backlog = 10; // 但是一般不要设置的太大

class TcpServer
{
public:
    TcpServer(const uint16_t &port, const std::string &ip = defaultip) 
    : listensock_(defaultfd), port_(port), ip_(ip)
    {
    }
    void InitServer()
    {
        listensock_ = socket(AF_INET, SOCK_STREAM, 0);
        printf("创建套接字成功, listensock_: %d\n", listensock_);

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        inet_aton(ip_.c_str(), &(local.sin_addr));

        bind(listensock_, (struct sockaddr *)&local, sizeof(local));
        printf("绑定套接字成功, listensock_: %d\n", listensock_);

        // Tcp是面向连接的，服务器一般是比较“被动的”，
        //服务器一直处于一种，一直在等待连接到来的状态
        listen(listensock_, backlog);
        printf("监听套接字成功, listensock_: %d\n", listensock_);
    }

    void Start()
    {
        printf("TCP服务器正在运行....");
        for (;;)
        {
            // 1. 获取新连接
            struct sockaddr_in client;//保存客户端的地址信息
            socklen_t len = sizeof(client);
            //类似recvfrom
            int sockfd = accept(listensock_, (struct sockaddr *)&client, &len);
            
            uint16_t clientport = ntohs(client.sin_port);//将客户端端口号拿出来
            char clientip[32];
            //将ip从网络字节序转换成主机序列并写进缓冲区clientip内
            inet_ntop(AF_INET, &(client.sin_addr), clientip, sizeof(clientip));
            printf("链接到一个客户端, sockfd: %d, client port: %d\n", 
            sockfd, clientport);

            // 2. 根据新连接来进行通信
            Service(sockfd);
            close(sockfd);//关闭文件描述符
        }
    }
    void Service(int sockfd)
    {
        // 测试代码
        char buffer[4096];
        while (true)
        {
            ssize_t n = read(sockfd, buffer, sizeof(buffer));
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "客户端说# " << buffer << std::endl;
                std::string echo_string = "服务器回答# ";
                Request r;
                Response rs;
                r.Deserialize(buffer);
                rs.cal(r);
                std::string temp;
                rs.Serialize(&temp);
                rs.DebugPrint();
                echo_string += temp;
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if(n==0)
            {
                std::cout<<"读到文件末尾"<<std::endl;
                sleep(1);
                break;
            }
            else
            {
                std::cout<<"读到出错"<<std::endl;
                sleep(1);
                break;
            }
        }
    }
    ~TcpServer() 
    {
        if(listensock_>0) close(listensock_);
    }

private:
    int listensock_;
    uint16_t port_;
    std::string ip_;
};
